import React, { useCallback, useEffect, useMemo, useState } from "react";
import { Table, Card, Button, Modal, message, Input } from "antd";
import { ColumnsType } from 'antd/es/table';
import { LibAppView } from '@/lib';
import { ReloadOutlined } from '@ant-design/icons';
import { useAdminRight } from "../../data/AdminPageAuth";
import { IWithLoadingApi } from "@/lib/AppView";

interface IResourceApproveProps {
    columns: ColumnsType<any>;
    listEndPoint: string;
    submitEndPoint: string;
    cancelEndPoint?: string;
    cancelStatus?: number;
    style?: React.CSSProperties;
    title: string;
    hideReview?: boolean;
    approveText?: string;
    onReview?: (data: any) => void;
    onBeforeApprove?: (data: any, loadingApi: IWithLoadingApi) => Promise<any>;
};
const { TextArea } = Input;

const ResourceApprove = LibAppView.withService<IResourceApproveProps>({
    "loadingOptions": {
        "controlled": true,
        "defaultVisible": true,
        "mountWithLoading": true,
        "skeletonProps": {
            "paragraph": {
                "rows": 6
            }
        }
    }
})((props) => {
    const [ listData, setListData ] = useState<any[]>([]);
    const hasApproveRight = useAdminRight("approver");
    const loadData = useCallback(() => {
        props.withLoadingApi.show();
        props.withServiceApi.send({
            endPoint: props.listEndPoint,
        }).then((resp: any) => {
            props.withLoadingApi.hide();
            setListData(resp.data || []);
        }).catch((err) => {
            props.withLoadingApi.hide();
        })
    }, []);
    
    const onApprove = useCallback((data: any, status: number, notHandleBeforeEvent?: boolean) => {
        const submitEndPoint = status === 1 ? props.submitEndPoint : props.cancelEndPoint || props.submitEndPoint;
        if(typeof props.onBeforeApprove === "function" &&  status === 1 && !notHandleBeforeEvent) {
            props.onBeforeApprove(data, props.withLoadingApi).then((nextSubmitData) => {
                props.withLoadingApi.show();
                    props.withServiceApi.send({
                        endPoint: submitEndPoint,
                        data: {
                            ...data,
                            ...(nextSubmitData || {})
                        }
                    }).then(() => {
                        props.withLoadingApi.hide();
                        loadData();
                    }).catch((err)=> {
                        props.withLoadingApi.hide();
                        typeof err !== "boolean" && message.error(err.message || "未知错误");
                    });
            });
        } else {
            const confirmText = (
                status === 1 ? "确认发布操作？" : (
                    <>
                        <label>拒绝发布，请填写拒绝理由：</label>
                        <TextArea
                            rows={4}
                            placeholder="请输入拒绝理由"
                            onChange={(e) => {
                                data.rejectReason = e.target.value;
                            }}
                            style={{ marginTop: 10 }}
                        >
                        </TextArea>
                    </>
                )
            );
            Modal.confirm({
                title: "确认操作",
                content: confirmText,
                onOk: () => {
                    props.withLoadingApi.show();
                    props.withServiceApi.send({
                        endPoint: submitEndPoint,
                        data: {
                            ...data,
                            approveMsg: data.rejectReason,
                            status
                        }
                    }).then(() => {
                        props.withLoadingApi.hide();
                        loadData();
                    }).catch((err)=> {
                        props.withLoadingApi.hide();
                        typeof err !== "boolean" && message.error(err.message || "未知错误");
                    });
                }});
        }
    }, []);
    const tableColumns = useMemo(() => {
        return hasApproveRight ? [
            ...props.columns,
            {
                title: "操作",
                key: "action",
                width: 240,
                fixed: true,
                render: (text: any, record: any) => {
                    return (<>
                        { !props.hideReview && <Button type="primary" onClick={()=> typeof props.onReview === "function" && props.onReview(record)}>预览</Button> }
                         <Button type="default" onClick={()=> onApprove(record, 1)}>{props.approveText || "发布"}</Button>
                         <Button type="dashed" onClick={()=> onApprove(record, props.cancelStatus || 0)}>拒绝</Button>
                    </>);
                }
            }
        ] : props.columns;
    }, [props.columns, listData])
    useEffect(() => {
        loadData();
    }, []);
    return (<section style={props.style}>
        <Card
            title={props.title}
            bordered={false}
            extra={<Button type="text" onClick={loadData}><ReloadOutlined /></Button>}
        >
            <Table
                columns={tableColumns}
                dataSource={listData}
            />
        </Card>
    </section>
    );
});

export default ResourceApprove;
